import { filter, keyBy, forEach, some } from 'lodash'
export const getDomHeight = async (id) => {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
      success: (res) => {
        const query = uni.createSelectorQuery() // 确保在页面上下文中调用
        
        setTimeout(() => {
          query
          .select(`${id}`) // 添加 # 号以正确匹配 ID 选择器
          .boundingClientRect((data) => {
            console.log(data)
            if (data) {
              const height = res.screenHeight - data.top
              resolve(`${height}`) // 使用 resolve 返回结果
            } else {
              reject(new Error('未找到指定的 DOM 元素'))
            }
          })
          .exec()
        }, 1000);
       
      },
      fail: (err) => {
        console.error('获取系统信息失败:', err)
        reject(err)
      }
    })
  })
}


export const navigatorjump = (url: string) => {
  uni.navigateTo({
    url: url
  })
}


//扁平数组转树状结构 fatherKey fatherKey父子上下级字段  glkey关联字段  id 主键字段
export const arrayToTree = (items: any, fatherKey: string, glkey: string) => {
  //寻找根节点，也就是父id为空的数据项 或者父ID找不到数据项
  // let rootItems = filter(items, { [fatherKey]: '' });
   let rootItems = items.filter((item: any) => !some(items, { [glkey]: item[fatherKey] }) || !item[fatherKey]);
  // rootItems = rootItems.concat(tsrootItems)
  const childrenItems = filter(items, item =>
    some(items, { [glkey]: item[fatherKey] })
  );

  const itemsByParentId = keyBy(items, glkey);

  forEach(childrenItems, item => {
    const parent = itemsByParentId[item[fatherKey]];
    if (!parent.children) {
      parent.children = [];
    }
    parent.children.push(item);
  });
  console.log(rootItems, "=====返回的数组")
  return rootItems;





}


//获取当前经纬度
/**
 * 获取当前位置的地址信息
 *
 * @returns 返回Promise对象，resolve时返回当前位置的经纬度信息，reject时返回undefined
 */
export const getLocationAddress = async () => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      // 'gcj02'
      type: 'gcj02',
      altitude: true,
      success: (res: any) => {
        const curLocation = {
          latitude: res.latitude + '',
          longitude: res.longitude + ''
        }
        console.log('获取到定位信息', curLocation)
        resolve(curLocation)
      },
      fail: (res) => {
        console.log('获取位置信息失败！')
        const { locationEnabled } = uni.getSystemSetting()
        if (locationEnabled) {
          uni.showToast({
            title: '请打开系统GPS或者允许微信访问地理位置',
            icon: 'none'
          })

        } else {
          uni.showToast({
            title: '请打开系统GPS或者允许微信访问地理位置',
            icon: 'none'
          })
        }
        resolve(null)
      }
    })
  })
}

//获取定位权限

export const getLocationAuth = async () => {
  return new Promise((resolve, reject) => {
    uni.authorize({
      scope: 'scope.userLocation',
      success: async (res) => {
        let jwd = await getLocationAddress()
        if (jwd) {
          resolve(jwd)
        } else {
          reject()
        }
      },
      fail: () => {
        uni.showModal({
          title: '提示',
          content: '请打开位置权限！',
          showCancel: false,
          confirmText: '去设置'
        }).then(() => {
          uni.openSetting()
        })
        reject()
      }
    })
  })
}
//计算经纬度距离
export function haversineDistance(lat1: number, lon1: number, lat2: number, lon2: number) {
  // 将经纬度从度转换为弧度
  const R = 6371; // 地球半径，单位：千米
  const dLat = (lat2 - lat1) * (Math.PI / 180);
  const dLon = (lon2 - lon1) * (Math.PI / 180);
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  // 计算距离，单位：米
  const distance = R * c * 1000;
  return distance;
}

/**
 * 获取url参数值
 * 
*/
export function getQueryVariable(data: any, variable: any) {
  var vars = data.split('&')
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=')
    if (pair[0] == variable) {
      return pair[1]
    }
  }
  return ''
}